import axios, { AxiosRequestConfig, Method, ResponseType } from "axios";
import { message } from "antd";
import _ from "lodash";
interface RequestType {
  url: string;
  data?: Object;
  params?: Object;
  method?: Method;
  headers?: Object;
  responseType?: ResponseType
}

axios.defaults.withCredentials = true;
axios.defaults.baseURL = "http://192.168.1.203:9529";

axios.interceptors.response.use(
  function (response) {
    console.log("responseresponse", response);
    // 对响应数据做点什么
    let result = _.cloneDeep(response);
    if (
      response["request"]["responseType"] &&
      response["request"]["responseType"] === "blob"
    ) {
      console.warn("res before", response);
      const data = response.data;
      const name = response.headers["content-disposition"];
      const reg = new RegExp("filename=(.*)");
      reg.test(name);
      result.data = {
        code: 0,
        isFile: true,
        data: {
          fileName: decodeURIComponent(RegExp.$1),
          data: data,
        },
        msg: "请求成功",
      };
      return result;
    } else {
      return response;
    }
  },
  function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

const checkFile = (file: any) => {
  return new Promise((resolve, reject) => {
    let fileReader = new FileReader();
    fileReader.onload = function () {
      try {
        let jsonData = JSON.parse(this.result as string); // 说明是普通对象数据，后台转换失败
        resolve({
          status: 'fail',
          data: jsonData,
        });
      } catch (error) {
        resolve({
          status: 'success',
          data: file,
        });
      }
    };
    fileReader.readAsText(file);
  });
};

const Request = function ({
  url,
  data = {},
  params = {},
  method,
  headers,
  ...config
}: RequestType) {
  const token = localStorage.getItem("userAuth")
    ? JSON.parse(localStorage.getItem("userAuth") as string).token
    : "";
  return new Promise((resolve: any, reject: any) => {
    let options: AxiosRequestConfig = {
      url,
      method: method || "GET",
      headers: {
        token: token,
        ...headers,
      },
      ...config,
      data,
      params,
    };
    axios(options)
      .then((response) => {
        console.log("response", response);
        if (response.status === 200) {
          // 请求成功
          if (response.data.code === 0) {
            // 如果是文件，进行特殊处理
            if (response.data.isFile) {
              checkFile(response.data.data.data).then((res: any) => {
                if (res.status === "success") {
                  resolve(response.data.data);
                } else {
                  message.error(res.data.msg);
                  reject(res.data);
                }
              });
            } else {
              resolve(response.data.data);
            }
          } else if (response.data.code === 401) {
            message.info(response.data.msg);
            // token失效重新登录
            localStorage.clear();
            window.location.href = "/";
          } else {
            // 如果是文件下载是否有结果判断
            if (
              response.headers["content-type"] ===
                "application/octet-stream;charset=UTF-8" ||
              response.headers["content-type"] ===
                "application/vnd.ms-excel;charset=UTF-8"
            ) {
              resolve("");
              return;
            }
            reject(response.data.msg);
            message.error(response.data.msg);
          }
        } else {
          message.error(response);
          reject(response);
        }
      })
      .catch((error) => {
        console.log("error", error);
        message.error(JSON.stringify(error.message));
        reject(error);
      });
  });
};

export default Request;
